import { lazyReportBatch } from '../export';
import { generateUniqueId } from '../utils';

const pageChange = () => {
  let oldUrl = '';

  window.addEventListener(
    'hashchange',
    (e) => {
      console.log('hashchange', e);

      const newUrl = e.newURL;
      const reportData = {
        from: oldUrl,
        to: newUrl,
        type: 'behavior',
        subType: 'hashChange',
        startTime: performance.now(),
        uuid: generateUniqueId(),
      };

      lazyReportBatch(reportData);

      oldUrl = newUrl;
    },
    true
  );

  let from = '';
  window.addEventListener(
    'popstate',
    (e) => {
      console.log('popstate', e);

      const to = window.location.href;
      const reportData = {
        from: from,
        to: to,
        type: 'behavior',
        subType: 'popstate',
        startTime: performance.now(),
        uuid: generateUniqueId(),
      };

      lazyReportBatch(reportData);

      from = to;
    },
    true
  );
};

export default pageChange;
